// src/store/auth.js (部分更新)
import { defineStore } from 'pinia'
import apiClient from '../api'
import { authApi } from '../api/auth'

export const useAuthStore = defineStore('auth', {
    state: () => ({
        token: localStorage.getItem('token') || null,
        user: JSON.parse(localStorage.getItem('user') || 'null'),
        userRole: localStorage.getItem('userRole') || null
    }),

    actions: {
        setToken(token) {
            this.token = token
            localStorage.setItem('token', token)
        },

        setUser(user) {
            this.user = user
            localStorage.setItem('user', JSON.stringify(user))
        },

        setUserRole(role) {
            this.userRole = role
            localStorage.setItem('userRole', role)
        },

        removeToken() {
            this.token = null
            this.user = null
            this.userRole = null
            localStorage.removeItem('token')
            localStorage.removeItem('user')
            localStorage.removeItem('userRole')
        },

        async login(credentials) {
            try {
                const response = await apiClient.post('/auth/login', credentials)
                const { token, user } = response.data

                // 确保后端返回了token和user
                if (token && user) {
                    this.setToken(token)  // 这里会存储到localStorage
                    this.setUser(user)
                    this.setUserRole(user.role)
                    return { success: true, user }
                } else {
                    return { success: false, error: '登录响应格式错误' }
                }
            } catch (error) {
                return { success: false, error: error.response?.data?.message || '登录失败' }
            }
        },

        async logout() {
            this.removeToken()
            this.setUser(null)
        },

        async fetchCurrentUser() {
            if (!this.token) return null

            try {
                const response = await authApi.getCurrentUser()
                this.setUser(response.data)
                return response.data
            } catch (error) {
                this.logout()
                throw error
            }
        },

        async updateProfile(userData) {
            try {
                const response = await authApi.updateProfile(userData)
                this.setUser(response.data)
                return response.data
            } catch (error) {
                throw error
            }
        }
    }
})
